package cn.chenhao.org.service.impl;

import cn.chenhao.basic.exception.BusinessException;
import cn.chenhao.basic.service.impl.BasicServiceImpl;
import cn.chenhao.org.domain.Employee;
import cn.chenhao.org.domain.Shop;
import cn.chenhao.org.mapper.EmployeeMapper;
import cn.chenhao.org.mapper.ShopMapper;
import cn.chenhao.org.service.IEmployeeService;
import cn.chenhao.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShopServiceImpl extends BasicServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IEmployeeService employeeService;

    @Override
    @Transactional
    public void settlement(Shop shop) {
        /**
         * 一：校验
         *      1.校验密码，看两次输入的密码是否一致
         *      2.校验用户名是否存在，存在则提醒登录，不存在就保存到数据库
         */
        // 1.校验密码
        Employee admin = shop.getAdmin();// 先获取当前店铺的管理员
        if (!admin.getPassword().equals(admin.getComfirmPassword())){// 通过两次输入的密码比较
            throw new BusinessException("请保持两次密码输入一致！");// 如果不一致，就抛出自定义业务异常
        }

        // 2.校验用户名是否存在
        Employee emp = employeeMapper.loadByUser(admin.getUsername());// 通过用户名查找
        if (emp != null){// 如果用户名存在，就抛出业务异常给用户，让其登录或其他操作
            throw new BusinessException("您已注册，请前往登录");
        }

        /**
         * 二：实现入驻
         */
        // 1.先保存管理员信息到employee表，并返回自增长id
        employeeService.add(admin);

        // 2.再保存店铺到shop表,并返回自增长id
        shop.setAdmin(admin);
        shopMapper.save(shop);

        // 3.添加完店铺后，要修改员工所属的店铺id
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);

    }
}
